package com.qingcheng.consumer;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.qingcheng.dao.SeckillGoodsMapper;
import com.qingcheng.pojo.seckill.SeckillGoods;
import com.qingcheng.pojo.seckill.SeckillOrder;
import com.qingcheng.service.order.WxPayService;
import com.qingcheng.util.SeckillStatus;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author: LDeng
 * @Date: 2020-07-24 10:53
 */

@Component
public class OrderMessageListener  implements MessageListener {

    public void onMessage(Message message) {
        String content = new String(message.getBody());
        System.out.println("监听到的消息：" + content);
        rollbackOrder(JSON.parseObject(content,SeckillStatus.class));

    }

    @Autowired
    private RedisTemplate redisTemplate;

    @Reference
    private WxPayService wxPayService;

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;


    //回滚库存
    public void rollbackOrder(SeckillStatus seckillStatus){
        if(seckillStatus==null){

        }
        //判断redis中是否存在对应的订单
        SeckillOrder order =(SeckillOrder) redisTemplate.boundHashOps("SeckillOrder").get(seckillStatus.getUsername());

        //如果存在， 开始回滚
        if(seckillStatus!=null){
            //关闭微信支付
//            Map<String,String> map=wxPayService.closePay(seckillStatus.getOrderId().toString());
//            if(map.get("return_code").equals("SUCCESS") && map.get("result_code").equals("SUCCESS")){
//
//            }
            //删除用户订单
            redisTemplate.boundHashOps("SeckillOrder").delete(seckillStatus.getUsername());

            //查询出商品数据
            SeckillGoods goods =(SeckillGoods) redisTemplate.boundHashOps("SeckillGoods_" + seckillStatus.getTime()).get(seckillStatus.getGoodsId());
            if(goods==null){
                //数据库中加载数据
              goods = seckillGoodsMapper.selectByPrimaryKey(seckillStatus.getGoodsId());
            }

            //库存递增
            Long SeckillGoodsCount=redisTemplate.boundHashOps("SeckillGoodsCount").increment(seckillStatus.getGoodsId(),1);
            goods.setStockCount(SeckillGoodsCount.intValue());

            //将商品数据同步到redis中

            redisTemplate.boundHashOps("SeckillGoods_"+seckillStatus.getTime()).put(seckillStatus.getGoodsId(),goods);
            redisTemplate.boundListOps("SeckillGoodsCountList_"+seckillStatus.getGoodsId()).leftPush(seckillStatus.getGoodsId());
            //清理用户抢单排队信息
            redisTemplate.boundHashOps("UserQueueCount").delete(seckillStatus.getUsername());
            redisTemplate.boundHashOps("UserQueueStatus").delete(seckillStatus.getUsername());

        }
    }
}
